package com.ruoyi.common.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信工具类
 * 用于调用微信官方API接口
 */
public class WeChatUtils {
    
    private static final Logger log = LoggerFactory.getLogger(WeChatUtils.class);
    
    // 微信API接口地址
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    private static final String GET_USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo";
    private static final String JSCODE_TO_SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session";
    
    private static final RestTemplate restTemplate = new RestTemplate();
    private static final ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * 获取微信access_token
     * @param appId 小程序/公众号的AppID
     * @param secret 小程序/公众号的AppSecret
     * @return access_token
     */
    public static String getAccessToken(String appId, String secret) {
        try {
            String url = GET_ACCESS_TOKEN_URL + "?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
            
            log.info("调用微信接口获取access_token: {}", url);
            
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                JsonNode jsonNode = objectMapper.readTree(response.getBody());
                
                if (jsonNode.has("access_token")) {
                    String accessToken = jsonNode.get("access_token").asText();
                    log.info("成功获取access_token: {}", accessToken);
                    return accessToken;
                } else if (jsonNode.has("errcode")) {
                    String errCode = jsonNode.get("errcode").asText();
                    String errMsg = jsonNode.get("errmsg").asText();
                    log.error("获取access_token失败: {} - {}", errCode, errMsg);
                    throw new RuntimeException("微信接口错误: " + errMsg);
                }
            }
            
            throw new RuntimeException("调用微信接口失败");
            
        } catch (Exception e) {
            log.error("获取微信access_token异常", e);
            throw new RuntimeException("获取微信access_token失败: " + e.getMessage());
        }
    }
    
    /**
     * 微信小程序登录凭证校验
     * @param appId 小程序的AppID
     * @param secret 小程序的AppSecret
     * @param jsCode 登录时获取的code
     * @return 包含openid和session_key的Map
     */

    /**
     * 获取微信用户信息
     * @param accessToken 接口调用凭证
     * @param openId 用户的唯一标识
     * @return 用户信息JSON字符串
     */

}